using System;
using System.Linq.Expressions;

namespace MvvmUtils.Common.Expressions
{
    public static class ExpressionExtensions
    {
        public static string GetPropertyName<TObject, TProperty>(
            this Expression<Func<TObject, TProperty>> propertySelector)
        {
            if (propertySelector == null) throw new ArgumentNullException("propertySelector");

            /* "obj => obj.Property"
             *         |----------|
             *             Body (MemberExpression)
             *            |-------|
             *              Member (Type: string)
             * */

            var memberExpression = propertySelector.Body as MemberExpression;
            if (memberExpression != null)
            {
                return memberExpression.Member.Name;
            }

            throw new ArgumentException(
                string.Format(
                    "propertySelector is not a valid property selector: \"{0}\".",
                    propertySelector),
                "propertySelector");
        }
    }
}